//
//  MyChatTableViewCell.m
//  weibo
//
//  Created by wudongyang on 16/6/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MyChatTableViewCell.h"
#import "DSAudioPlayTool.h"
#import "UIImageView+WebCache.h"

#define LABELWIDTH 250
@implementation MyChatTableViewCell
- (void)dealloc
{
    [_message release];
    [_contentsLabel release];
    [_bgImageView release];
    [_contents release];
    [_timeLabel release];
    [super dealloc];
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createSubViews];
    }
    return self;
}

- (void)createSubViews{
    NSLog(@"=====");
    self.contentView.backgroundColor = DSRGBA(235, 235, 235, 1);
    self.bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 60, 80)];
    
    self.bgImageView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.bgImageView];
    [_bgImageView release];
    
    self.contentsLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, LABELWIDTH, 60)];
    
    [self.contentView addSubview:self.contentsLabel];
    [_contentsLabel release];
    // 设置无限行数
    self.contentsLabel.numberOfLines = 0;
    // 换行模式:按文字换行
    self.contentsLabel.lineBreakMode = NSLineBreakByWordWrapping;
    // 开启交互
    self.contentsLabel.userInteractionEnabled = YES;
//    self.contentsLabel.
    // 在此方法做一些初始化操作
    // 1.给label添加敲击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(messageLabelTap:)];
    [self.contentsLabel addGestureRecognizer:tap];
    [tap release];
    

    // 创建时间label
    self.timeLabel = [[UILabel alloc] init];
    self.timeLabel.backgroundColor = DSRGBA(184, 184, 184, 1);
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.font = [UIFont systemFontOfSize:14];
    [self addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgImageView.mas_bottom).offset(10);
        make.size.mas_equalTo(CGSizeMake(45, 15));
        make.center.centerX.mas_equalTo(self.mas_centerX);
        make.bottom.equalTo(self).offset(-10);
        
    }];
    


}
// 显示自己的
-(void)setMessage:(EMMessage *)message{
    if (_message != message) {
        [_message release];
        _message = [message retain];
    }
    id body = [message.messageBodies lastObject];
    // 聊天文本消息体
    if ([body isKindOfClass:[EMTextMessageBody class]]) {
        EMTextMessageBody *textBody = body;
        self.contentsLabel.text = textBody.text;
        CGFloat height = [[self class] heightForCell:textBody.text];
        CGRect tempRect = self.contentsLabel.frame;
        tempRect.size.height = height;
        self.contentsLabel.frame = tempRect;
        [self.contentsLabel sizeToFit];
        
        UIImage *image = [UIImage imageNamed:@"chat_sender_bg"];
        image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.6, image.size.width * 0.4, image.size.height * 0.3, image.size.width * 0.4)];
        // 图片拉伸
//        image = [image stretchableImageWithLeftCapWidth:image.size.width / 2 topCapHeight:image.size.height / 2];
        self.bgImageView.image = image;
        
        // 将时间戳转换成时间
        NSDate* detaildate=[NSDate dateWithTimeIntervalSince1970:textBody.message.timestamp /1000];
        
        NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
        
        //设定时间格式,这里可以设置成自己需要的格式
        
        [dateFormatter setDateFormat:@"HH:mm"];
        
        NSString* currentDateStr = [dateFormatter stringFromDate:detaildate];
        self.timeLabel.text = currentDateStr;
        NSLog(@"date:%@",currentDateStr);

        // 添加约束
        [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentsLabel).mas_equalTo(UIEdgeInsetsMake(-10, -15, -10, -15));
            
        }];
        // 聊天语音消息体
    }else if ([body isKindOfClass:[EMVoiceMessageBody class]]){
    
        self.contentsLabel.attributedText = [self voiceAtt];
    // 聊天图片消息体
    }else if ([body isKindOfClass:[EMImageMessageBody class]]){
        [self showImage];
    
    }else{
    self.contentsLabel.text = @"未知类型";
    }
    // 添加约束
    [self.contentsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self).mas_equalTo(-20);
        make.top.equalTo(self).mas_equalTo(15);
        
    }];
    // 限制label最宽的宽度是多少
    self.contentsLabel.preferredMaxLayoutWidth = LABELWIDTH;
}
// 使用富文本显示图片
-(void)showImage{
// 获取图片消息体
    EMImageMessageBody *imgBody = self.message.messageBodies[0];
    // 图片消息预存图的尺寸
    CGRect thumbnailFrm = (CGRect){0,0,imgBody.thumbnailSize};
    // 设置Label的尺寸足够显示UIImageView
    NSTextAttachment *imgAttach = [NSTextAttachment new];
    imgAttach.bounds = thumbnailFrm;
    NSAttributedString *imgAtt = [NSAttributedString attributedStringWithAttachment:imgAttach];
    self.contentsLabel.attributedText = imgAtt;
    
    //1.cell里添加一个UIImageView
    UIImageView *chatImageView = [UIImageView new];
    [self.contentsLabel addSubview:chatImageView];
    chatImageView.backgroundColor = [UIColor redColor];
    //2.设置图片控件为缩略图的尺寸
    chatImageView.frame = CGRectMake(thumbnailFrm.origin.x + 60, -12, 100, 90);
    //3.下载图片
    NSFileManager *manager = [NSFileManager defaultManager];
    // 如果本地图片存在,直接从本地显示图片
    UIImage *palceImg = [UIImage imageNamed:@"downloading"];
    if ([manager fileExistsAtPath:imgBody.thumbnailLocalPath]) {
        [chatImageView sd_setImageWithURL:[NSURL fileURLWithPath:imgBody.thumbnailLocalPath] placeholderImage:palceImg];
    }else{
    
        //如果本地图片不存, 从图片加载图片
        [chatImageView sd_setImageWithURL:[NSURL URLWithString:imgBody.thumbnailLocalPath] placeholderImage:palceImg];
    
    }
    UIImage *image = [UIImage imageNamed:@"chat_send_nor"];
    image = [image resizableImageWithCapInsets:(UIEdgeInsetsMake(image.size.height * 0.6, image.size.width * 0.4, image.size.height * 0.3, image.size.width * 0.4))];
//    image = [image stretchableImageWithLeftCapWidth:image.size.width / 2 topCapHeight:image.size.height / 2];
    self.bgImageView.image = image;
    // 添加约束
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(chatImageView).mas_equalTo(UIEdgeInsetsMake(-5, -15, -5, -15));
    }];
    

}
+(CGFloat)heightForCell:(NSString *)content{

    CGSize size = CGSizeMake(LABELWIDTH, 10000);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
    
    CGRect rect = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return rect.size.height;


}
// 返回cell的高度
-(CGFloat)cellHeight{

    // 1.重新布局子控件
    [self layoutIfNeeded];
    return 5 + 10 + self.contentsLabel.bounds.size.height + 10 + 5;

}
//返回语音富文本
-(NSAttributedString *)voiceAtt{
    
    // 创建一个可变的富文本
    NSMutableAttributedString *voiceAttM = [[NSMutableAttributedString alloc] init];
    
    // 2.发送方：富文本 ＝ 时间 + 图片
    // 2.1 拼接时间
    // 获取时间
    EMVoiceMessageBody *voiceBody = self.message.messageBodies[0];
    NSInteger duration = voiceBody.duration;
    NSString *timeStr = [NSString stringWithFormat:@"%ld'",duration];
    NSAttributedString *timeAtt = [[NSAttributedString alloc] initWithString:timeStr];
    [voiceAttM appendAttributedString:timeAtt];
    
    
    // 2.1拼接图片
    UIImage *receiverImg = [UIImage imageNamed:@"chat_sender_audio_playing_full"];
    
    // 创建图片附件
    NSTextAttachment *imgAttachment = [[NSTextAttachment alloc] init];
    imgAttachment.image = receiverImg;
    imgAttachment.bounds = CGRectMake(0, -7, 30, 30);
    // 图片富文本
    NSAttributedString *imgAtt = [NSAttributedString attributedStringWithAttachment:imgAttachment];
    [voiceAttM appendAttributedString:imgAtt];
    
    return [voiceAttM copy];
    
}





//messagelabel 点击的触发方法
-(void)messageLabelTap:(UITapGestureRecognizer *)recognizer{
    
    NSLog(@"%s",__func__);
    //播放语音
    //只有当前的类型是为语音的时候才播放
    //1.获取消息体
    id body = self.message.messageBodies[0];
    
    if ([body isKindOfClass:[EMVoiceMessageBody class]]) {
        
        NSLog(@"播放我发出的语音");
        [DSAudioPlayTool playWithMessage:self.message msgLabel:self.contentsLabel receiver:NO];
        
    }
   
    
}
@end
